package com.namo.cchfile.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 *
 * @author WangXin
 * @date 2021/3/20 16:34
 */
@Configuration
@RefreshScope
@Slf4j
public class MinioConfig {

    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.bucketName}")
    private String bucketName;
    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.secretKey}")
    private String secretKey;

    /**
     * 配置存储桶，如果不存在则创建存储桶
     * @return 存储桶实例
     */
    @Bean
    public MinioClient minioClient() {
        MinioClient client = MinioClient
                .builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
        try {
            boolean isExist = client.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (isExist){
                log.info("存储桶已经存在！");
            }else {
                //创建存储桶
                client.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                log.info("创建存储桶成功！");
            }
        }catch (Exception e){
            log.error("存储桶错误！"+e.getMessage());
        }
        return client;
    }
}
